package com.test.murali;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

public class PaajiJokes extends Activity implements ViewTreeObserver.OnGlobalLayoutListener{
	
	
	ViewGroup container;
	TextView textView;
	Button previous;
	Button next;
	int width;
	int height;
	int position = 1;
	ImageButton email;
	Joke joke;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setUpViews();
    }

	private void setUpViews() {
		container=(ViewGroup)findViewById(R.id.container_jokes);
		textView= (TextView)findViewById(R.id.textView);

		
		previous = (Button)findViewById(R.id.previous);
		next = (Button)findViewById(R.id.next);
		
		email = (ImageButton)findViewById(R.id.imageButton1);

		container.setVisibility(View.INVISIBLE);
		container.getViewTreeObserver().addOnGlobalLayoutListener(this);
		
		previous.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
           	 moveBack();
            }
        });
		
		next.setOnClickListener(new View.OnClickListener() {
           public void onClick(View v) {
           	moveForward();
           }
       });
		
		email.setOnClickListener(new View.OnClickListener() {
	           public void onClick(View v) {
	           	startEmail();
	           }
	       });
		
	}
	
	protected void startEmail() {
		/* Create the Intent */
		final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

		/* Fill it with Data */
		emailIntent.setType("plain/text");
		emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{""});
		emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Fwd: Paaji Joke");
		emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, joke.getDescription());

		/* Send it off to the Activity-Chooser */
		startActivity(Intent.createChooser(emailIntent, "Send mail..."));
					
	}

	private void moveBack() {
		if(position > 1) {
    		position = position - 1 ;
    		loadJoke(position);
    	}
	}
	
	private void moveForward() {
       		position = position +1 ;
       		loadJoke(position);
	}
	
	public void onGlobalLayout() {
		// TODO Auto-generated method stub
		container.getViewTreeObserver().removeGlobalOnLayoutListener(this);
		width=textView.getMeasuredWidth();
		height=textView.getMeasuredHeight();
		loadJoke(position);
	}

	private void loadJoke(int position) {
		JokesService jokesService = new JokesService();
		joke = jokesService.getJoke(position);
		
		textView.setText(joke.getDescription());
		
		container.setVisibility(View.VISIBLE);
		
	}
}